package com.fuqi.framework.utils;

import android.graphics.Color;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.widget.TextView;

import com.fuqi.android.zhongcai.base.ApiUrl;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {

	/**
	 * 将字符串转double
	 * 
	 * @param value
	 * @return
	 */
	public static double parseDouble(String value) {
		try {
			return Double.parseDouble(value);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	public static float parseFloat(String value) {
		try {
			return Float.parseFloat(value);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	public static int parseInt(String value) {
		try {
			return Integer.parseInt(value);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	public static long parseLong(String value) {
		try {
			return Long.parseLong(value);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	public static boolean isEmpty(String str) {
		return str == null || str.trim().length() == 0 || "null".equals(str);
	}

	public static boolean isNotEmpty(String str) {
		return !StringUtil.isEmpty(str);
	}

	/**
	 * 输入时改变字体
	 * 
	 * @param txt
	 *            需要显示的值
	 * @param totlValue
	 *            总字符串
	 * @param chageText
	 *            改变颜色的字符串
	 */
	public static void onChageTextColor(TextView txt, String totlValue,
			String chageText) {
		SpannableString ss = new SpannableString(totlValue);// getResources().getString(R.string.linkify)
		if (chageText == null || chageText.equals("")) {
			chageText = "-1";
		}
		Pattern p = Pattern.compile(chageText);
		Matcher m = p.matcher(ss);
		while (m.find()) {
			int start = m.start();
			int end = m.end();
			ss.setSpan(new ForegroundColorSpan(Color.RED), start, end,
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		txt.setText(ss);
	}

	/**
	 * 将json 数组转换为Map 对象
	 * 
	 * @param jsonString
	 * @return
	 */
	public static Map<String, String> getMap(String jsonString) {
		JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(jsonString);
			@SuppressWarnings("unchecked")
			Iterator<String> keyIter = jsonObject.keys();
			String key;
			String value;
			Map<String, String> valueMap = new HashMap<String, String>();
			while (keyIter.hasNext()) {
				key = (String) keyIter.next();
				value = (String) jsonObject.get(key);
				valueMap.put(key, value);
			}
			return valueMap;
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 把json 转换为 ArrayList 形式
	 * 
	 * @return
	 */
	public static List<Map<String, String>> getListMap(String jsonString  ) {
		List<Map<String, String>> list = null;
		try {
			JSONArray jsonArray = new JSONArray(jsonString);
			JSONObject jsonObject;
			list = new ArrayList<Map<String, String>>();
			for (int i = 0; i < jsonArray.length(); i++) {
				jsonObject = jsonArray.getJSONObject(i);
				list.add(getMap(jsonObject.toString()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 把以 separator 为分隔的字符串转换为 ArrayList 形式
	 * @param str 字符串
	 * @param separator 分隔符
	 * @return
	 */
	public static List<String> getList(String str ,String separator) {
		List<String> list = null;
		if(isNotEmpty(str)) {
			String[] atemp = str.split(separator);
			list = Arrays.asList(atemp);
		}
		if(list == null) list = new ArrayList<>();
		return list;
	}

	/**
	 * 把以 separator 为分隔的字符串转换为 ArrayList 形式
	 * @param str 字符串
	 * @param separator 分隔符
	 * @return
	 */
	public static ArrayList<String> getListWithPath(String str ,String separator) {
		ArrayList<String> list = new ArrayList<>();
		if(isNotEmpty(str)) {
			String[] atemp = str.split(separator);
			for (int i = 0;i < atemp.length ; i++){
				list.add(ApiUrl.getDefaultHost() + atemp[i]);
			}
		}
		if(list == null) list = new ArrayList<String>();
		return list;
	}
	
	/**
	 * 把列表转为json格式
	 * @param maps
	 * @return
	 */
	public static String getString(List<Map<String, String>> maps){
		JSONArray array = new JSONArray();
		for (Map<String, String> map : maps) {
			JSONObject obj = new JSONObject(map);
			array.put(obj);
		}
		return array.toString();
	}

	/**
	 * 将数组转成字符串
	 * @param lists
	 * @return
	 */
	public static String getListString(List<String> lists){
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < lists.size(); i++) {
			if(i != 0 )
				sb.append(",");
			sb.append(lists.get(i));
		}
		return sb.toString();
	}

	/**
	 * 将数组转成字符串
	 * @param lists
	 * @return
	 */
	public static String getListString(String[] lists){
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < lists.length; i++) {
			if(i != 0 )
				sb.append(",");
			sb.append(lists[i]);
		}
		return sb.toString();
	}
	
	public static String convertStreamToString(InputStream is) {      
         BufferedReader reader = new BufferedReader(new InputStreamReader(is));      
         StringBuilder sb = new StringBuilder();      
     
         String line = null;      
        try {      
            while ((line = reader.readLine()) != null) {      
                 sb.append(line + "\n");      
             }      
         } catch (IOException e) {      
             e.printStackTrace();      
         } finally {      
            try {      
                 is.close();      
             } catch (IOException e) {      
                 e.printStackTrace();      
             }      
         }      
        Log.e("ccqx", "convertStreamToString"+sb.toString());
        return sb.toString();      
     }
	

	public static String getUnitString(String intger){
		String resultStr = "";
		String intger2= "";
		boolean negative = false;
		DecimalFormat formatter = new DecimalFormat("####.###E0");
		//DecimalFormat formatter2 = new DecimalFormat("#");
		DecimalFormat formatter2 = new DecimalFormat("0.00");
		try {
			if(intger.indexOf(".")>-1) {negative = true; intger2 = intger.substring(0,intger.indexOf("."));}
			else {
				intger2 = intger;
			}
			if(intger2.length() > 8){
				resultStr = formatter.format(Long.valueOf(intger2)).split("E")[0];
				if(resultStr.length() > 4) resultStr = resultStr.substring(0, 4);
				if(resultStr.indexOf(".") == resultStr.length() - 1) resultStr = resultStr.substring(0,resultStr.length() - 1);
				resultStr += "亿";
			}else if(intger2.length() > 4){
				resultStr = formatter.format(Long.valueOf(intger2)).split("E")[0];
				if(resultStr.length() > 4) resultStr = resultStr.substring(0, 4);
				if(resultStr.indexOf(".") == resultStr.length() - 1) resultStr = resultStr.substring(0,resultStr.length() - 1);
				resultStr += "万";
			}else if(intger2.length() > 3){
				resultStr = formatter2.format(Float.valueOf(intger2)/10000);
				resultStr += "万";
			}else{
				resultStr = intger;
			}
		}catch (Exception err){
			
		}
		
		return resultStr;
	}
	
	public static String getUnitString2(String intger){
		String resultStr = getUnitString2(Double.valueOf(intger));
		return resultStr;
	}
	
	public static String getUnitString2(double intger){
		String resultStr = "";
		try {
			resultStr = String.format("%.2f", intger);
		}catch (Exception err){
			
		}
		return resultStr;
	}
	public static String getUnitString3(double intger){
		String resultStr = "";
		try {
			resultStr = String.format("%.3f", intger);
			if (resultStr.endsWith("0")) {
				resultStr = resultStr.substring(0, resultStr.length()-1);
			}
		}catch (Exception err){
			
		}
		return resultStr;
	}


	public static String getPercent(double y, double z) {
		if(y == 0) return "无";
		String baifenbi = "";// 接受百分比的值
		double baiy = y * 1.0;
		double baiz = z * 1.0;
		double fen = baiy / baiz;
		// NumberFormat nf = NumberFormat.getPercentInstance();注释掉的也是一种方法
		// nf.setMinimumFractionDigits( 2 ); 保留到小数点后几位
		DecimalFormat df1 = new DecimalFormat("##.00");
		// ##.00%
		// 百分比格式，后面不足2位的用0补齐
		// baifenbi=nf.format(fen);
		baifenbi = df1.format(fen);
		return baifenbi +"%";
	}

}
